package com.lancoo.answer.view.fragment.option

import android.os.Bundle
import android.os.Handler
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.view.animation.TranslateAnimation
import androidx.databinding.ObservableArrayList
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.lancoo.answer.R
import com.lancoo.answer.component.InteractWebView
import com.lancoo.answer.databinding.EvFragmentLookingOptionBinding
import com.lancoo.answer.databinding.EvViewItemOptionBinding
import com.lancoo.answer.helper.recyclerview.BindingViewAdapter
import com.lancoo.answer.helper.recyclerview.BindingViewHolder
import com.lancoo.answer.helper.recyclerview.SingleTypeAdapter
import com.lancoo.answer.model.AnswerConstant
import com.lancoo.answer.model.ConstantBean
import com.lancoo.answer.model.bean.EvOptionBean
import com.lancoo.answer.model.bean.Item
import com.lancoo.answer.model.bean.Ques
import com.lancoo.answer.util.CustomPictureTextViewUtil
import com.lancoo.answer.util.DensityUtils
import com.lancoo.answer.view.base.BaseVMFragment
import com.lancoo.answer.widget.SplitView
import com.lancoo.answer.widget.combinationView.FillContextAnswerResultView
import com.rxjava.rxlife.RxLife
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import java.util.concurrent.TimeUnit

/**
 * Created by Dadong on 2021/12/27
 * Describe: 词汇匹配题原题查看，答题点抽题
 *
 */
class OptionOriginalLookingFragment : BaseVMFragment<EvFragmentLookingOptionBinding>() {
    private val TAG = "OptionLookingFragment"

    private var typeIndex = 0
    private var quesIndex = 0
    private var childIndex = 0
    private var defaultLoadIndex = 0
    private var itemIndex = -1
    private lateinit var ques: Ques
    private var itemSortIndex: String = "" //当前选择的序号
    private var optionList = ObservableArrayList<EvOptionBean>()
    private lateinit var multiChildFragment: MultiChildFragment
    private lateinit var convertView: View

    private val mAdapter: SingleTypeAdapter<EvOptionBean> by lazy {
        SingleTypeAdapter(requireContext(), R.layout.ev_view_item_option, optionList)
    }

    companion object {
        fun loadFragment(
            typeIndex: Int,
            quesIndex: Int,
            defaultLoadChildIndex: Int,
            defaultLoadItemIndex: Int
        ): Fragment? {
            val mBundle = Bundle()
            mBundle.putInt(AnswerConstant.KEY_TYPEINDEX, typeIndex)
            mBundle.putInt(AnswerConstant.KEY_QUESINDEX, quesIndex)
            mBundle.putInt(AnswerConstant.KEY_LOADCHILDINDEX, defaultLoadChildIndex)
            mBundle.putInt(AnswerConstant.KEY_LOADITEMINDEX, defaultLoadItemIndex)
            val optionLookingFragment = OptionOriginalLookingFragment()
            optionLookingFragment.arguments = mBundle
            return optionLookingFragment
        }
    }

    override fun initData() {
        if (ConstantBean.constantExamBean == null) {
            return
        }
        val kindBeanList = ConstantBean.constantExamBean!!.TypeList
        typeIndex = requireArguments().getInt(AnswerConstant.KEY_TYPEINDEX)
        quesIndex = requireArguments().getInt(AnswerConstant.KEY_QUESINDEX)
        childIndex = requireArguments().getInt(AnswerConstant.KEY_LOADCHILDINDEX)
        defaultLoadIndex = requireArguments().getInt(AnswerConstant.KEY_LOADITEMINDEX)
        ques = kindBeanList!![typeIndex].QuesList!![quesIndex]
        childIndex = ques.currentLoadChildIndex
        defaultLoadIndex = ques.ChildList!![childIndex].currentLoadItemIndex
        if (childIndex ==-1){
            childIndex = 0
        }
        if (defaultLoadIndex >= 0 && defaultLoadIndex < ques.ChildList!![childIndex].ItemList!!.size) {
            itemSortIndex =
                ques.ChildList!![childIndex].ItemList!![defaultLoadIndex].ItemSortIndex!!
        } else {
            itemSortIndex = ques.ChildList!![0].ItemList!![0].ItemSortIndex!!
        }
        initWeb()
        initAnswer()
    }

    override fun initView(view: View) {
        convertView = view
    }

    override fun getLayoutId(): Int {
        return R.layout.ev_fragment_looking_option
    }

    private fun initWeb() {
        var childAsk = ""
        var dealAsk = ""
        ques.ChildList!!.forEach {
            dealAsk = it.ChildAsk!!
            if (ques.SpecialFeatureCodes == "47|101") {
                dealAsk =
                    it.ChildAsk?.replaceFirst(">", ">${it.ItemList!![0].SortIndex}. ")!!
            }
            childAsk += dealAsk
        }
        mBinding.interactWv.setIsIndentation(ques.ChildList!![childIndex].IsIndentChildAsk)
        mBinding.interactWv.setQues(ques)
        mBinding.interactWv.initWebView(
            requireActivity(),
            childAsk!!,
            object : InteractWebView.Callback {
                override fun finishCallback() {
                    adjustFontSize()
                    initLayout()
                    mBinding.interactWv.showOrHideAnalysisButton(0)
                    wvLoadUrl(itemSortIndex)
                }

                override fun clickCallback(position: String) {
                    itemSortIndex = position
                    wvLoadUrl(itemSortIndex)
                    if (getRealItem() != null) {
                        showResultView(getRealItem()!!)
                    }
                }
            }
        )
        if (getRealItem() != null) {
            showResultView(getRealItem()!!)
        }
    }

    private fun initAnswer() {
        multiChildFragment =
            MultiChildFragment.loadFragment(
                typeIndex,
                quesIndex,
                childIndex
            ) as MultiChildFragment

        multiChildFragment.setPageChangeCallback(object : MultiChildFragment.PageChangeCallback {
            override fun callback(position: Int) {
                if (itemIndex == -1){
                    itemIndex = 0
                }
                childIndex = position
                itemSortIndex = ques.ChildList!![childIndex].ItemList!![itemIndex].ItemSortIndex!!
                wvLoadUrl(itemSortIndex)
                itemIndex = -1
            }
        })
        childFragmentManager
            .beginTransaction()
            .replace(mBinding.flAnswer.id, multiChildFragment!!, TAG)
            .commit()
    }

    /**
     *   答题点下划线，高亮等等绘制
     *   词汇匹配'm'需要展示标准答案
     */
    private fun wvLoadUrl(position: String = "-1") {
        mBinding.interactWv.scrollPosition(position)
        ques.ChildList!!.forEach {
            it.ItemList!!.forEachIndexed { index, item ->
                mBinding.interactWv.loadOriginUrl(
                    item,
                    position == item.ItemSortIndex.toString(),
                    true
                )
            }
        }
    }

    fun showResultView(item: Item) {
        if (ConstantBean.taskControlBean!!.trainSence == 1 || ConstantBean.taskControlBean!!.trainSence ==2
            || ConstantBean.taskControlBean!!.trainSence ==3){
            return
        }
        val fillContextAnswerResultView: FillContextAnswerResultView =
            mBinding.resultView.root.findViewById(R.id.fill_context_answer)
        val typeNo = ques.TypeNo
        fillContextAnswerResultView.setFillResult(item)
        mBinding.resultView.root.findViewById<View>(R.id.ll_close)
            .setOnClickListener { v: View? -> mBinding.resultView.root.visibility = View.GONE }
        if (TextUtils.equals("m", typeNo)) { //匹配题只显示答案解析
            fillContextAnswerResultView.onlyShowAnalysis()
        }
        val ctrlAnimation = TranslateAnimation(
            TranslateAnimation.RELATIVE_TO_SELF, 0f, TranslateAnimation.RELATIVE_TO_SELF, 0f,
            TranslateAnimation.RELATIVE_TO_SELF, 1f, TranslateAnimation.RELATIVE_TO_SELF, 0f
        )
        ctrlAnimation.duration = 400
        mBinding.resultView.root.visibility = View.VISIBLE
        mBinding.resultView.root.startAnimation(ctrlAnimation)
    }

    //获取Item
    fun getRealItem(): Item? {
        ques.ChildList!!.forEach {
            it.ItemList!!.forEachIndexed { index, item ->
                if (item.ItemSortIndex == itemSortIndex) {
                    return item
                }
            }
        }
        return null
    }

    //获取序号在ItemList 中的位置
    fun getRealIndex(): Int {
        ques.ChildList!!.forEachIndexed { index, child ->
            child.ItemList!!.forEachIndexed { itemIndex, item ->
                if (item.ItemSortIndex == itemSortIndex) {
                    childIndex = index
                    return itemIndex
                }
            }
        }
        return 0
    }

    //获取序号在ItemList 中的位置
    fun getChildIndex(): Int {
        ques.ChildList!!.forEachIndexed { index, child ->
            child.ItemList!!.forEachIndexed { itemIndex, item ->
                if (item.ItemSortIndex == itemSortIndex) {
                    childIndex = index
                    return childIndex
                }
            }
        }
        return 0
    }

    /**
     * 跳转到指定小题
     * @param itemIndex 答题点下标
     */
    fun jumpToAimChildFragment(childIndex: Int, itemIndex: Int) {
        if (mBinding != null) {
            Handler().postDelayed({
                itemSortIndex = ques.ChildList!![childIndex].ItemList!![itemIndex].ItemSortIndex!!
                wvLoadUrl(itemSortIndex)
                this.childIndex = childIndex
                this.itemIndex = itemIndex
                multiChildFragment.setCurrentItem(childIndex)
            }, 200)
        }
    }

    fun adjustFontSize() {
        if (mBinding.interactWv != null) {
            mBinding.interactWv.setFontSize()
        }
        multiChildFragment.adjustFontSize()
    }

    fun initLayout() {
        if (convertView == null) {
            return
        }
        val splitView: SplitView = convertView!!.findViewById<SplitView>(R.id.split_view)
        Single.timer(250, TimeUnit.MILLISECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .`as`(RxLife.`as`(this))
            .subscribe({ splitView.initLayout(0.5f) }) { throwable: Throwable? -> }
    }
}